﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;

namespace FtpWorkerRole.FtpServer
{
    class DataSocketHandler
    {
        private FtpSocketHandler handler;
        private TcpClient dataClient;

        public DataSocketHandler(FtpSocketHandler handler)
        {
            this.handler = handler;            
        }

        public bool open()
        {
            try
            {
                dataClient = new TcpClient(handler.dataChannelSocketAddress, handler.dataChannelSocketPort);
            }
            catch (SocketException)
            {
                dataClient = null;
            }
            return dataClient != null;
        }
        public void close()
        {
            if (dataClient == null)
            {
                return;
            }
            try
            {
                if (dataClient.GetStream() != null)
                {
                    dataClient.GetStream().Flush();
                    dataClient.GetStream().Close();
                }
            }
            catch (Exception)
            {
            }
            try
            {
                dataClient.Close();
            }
            catch (Exception)
            {
            }
            dataClient = null;
        }

        public int readData(byte[] data)
        {
            return dataClient.GetStream().Read(data, 0, data.Length);            
        }

        public void sendData(byte[] data)
        {
            sendData(data, data.Length);
        }
        public void sendData(byte[] data, int length)
        {
            Utils.sendData(dataClient, data, length);
        }
        public void sendString(string message)
        {
            byte[] data = Encoding.ASCII.GetBytes(message);
            sendData(data, data.Length);
        }
    }
}
